<template>
  <StyleProvider>
    <router-view></router-view>
  </StyleProvider>
</template>
<script setup lang="ts">
import { StyleProvider } from "ant-design-vue";
import { onMounted, onUnmounted } from "vue";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { useTradingPanels } from "@/composables/trading-controller/useTradingPanels";
import { useSoundManager } from "@/composables/useSoundManager";
import { ctpService } from "@/services/ctpService";
import { cleanupCurrentDirCache } from "./services/cacheManager";

// 使用交易面板管理组合式函数
const { closeAllTradingPanels } = useTradingPanels();

// 使用声音管理器（在应用级别初始化）
const { initSoundManager, cleanup: cleanupSoundManager } = useSoundManager();

let unlistenCloseRequested: (() => void) | null = null;
// 初始化声音管理器
initSoundManager();
// 监听主窗口关闭事件
onMounted(async () => {
  try {
    const mainWindow = getCurrentWindow();

    // 监听窗口关闭请求事件
    unlistenCloseRequested = await mainWindow.onCloseRequested(async (event) => {
      // 检查当前窗口是否为主窗口（面板条）
      const currentWindowLabel = mainWindow.label;

      // 只有主窗口或面板条窗口关闭时才执行清理流程
      if (
        currentWindowLabel === "main" ||
        currentWindowLabel.includes("trading-controller")
      ) {
        try {
          // 1. 关闭所有交易面板
          await closeAllTradingPanels();

          // 2. 清理CTP服务资源
          await ctpService.cleanup();

          // 3. 清理缓存目录（保留最新10个会话）
          await cleanupCurrentDirCache();
        } catch (error) {}
      } else {
      }

      // 允许窗口关闭
      // 注意：不需要调用 event.preventDefault()，让窗口正常关闭
    });
  } catch (error) {}
});

// 组件卸载时清理监听器
onUnmounted(() => {
  // 清理声音管理器
  cleanupSoundManager();

  // if (unlistenCloseRequested) {
  //   unlistenCloseRequested();
  //   unlistenCloseRequested = null;
  // }
});
</script>

<style>
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

div,
span,
p {
  margin: 0;
  padding: 0;
}

#app {
  height: 100%;
  width: 100%;
}
</style>
